package com.cn.kehong.service;

import com.cn.kehong.api.IDataSubmissionYyService;
import com.cn.kehong.dao.DataSubmissionYyMapper;
import com.cn.kehong.domain.DataSubmissionYy;
import com.cn.kehong.domain.DataSubmissionYyExample;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DataSubmissionYyServiceImpl implements IDataSubmissionYyService {

    @Autowired
    private DataSubmissionYyMapper dataSubmissionYyMapper;

    @Override
    public List<DataSubmissionYy> getDataSubmissionYyListById(String submissionId) throws Exception {
        if(StringUtils.isEmpty(submissionId)){
            return Lists.newArrayList();
        }
        DataSubmissionYyExample example = new DataSubmissionYyExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andSubmissionIdEqualTo(submissionId);
        example.setOrderByClause("sort_index asc");
        List<DataSubmissionYy> list = dataSubmissionYyMapper.selectByExample(example);
        return list;
    }

    @Override
    public String addDataSubmissionYy(List<DataSubmissionYy> dataSubmissionYys) throws Exception {
        if(CollectionUtils.isEmpty(dataSubmissionYys)){
            return "数组为空！";
        }
        int count = dataSubmissionYyMapper.batchInsertDataSubmissionYy(dataSubmissionYys);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateDataSubmissionYy(List<DataSubmissionYy> dataSubmissionYys) throws Exception {
        if(CollectionUtils.isEmpty(dataSubmissionYys)){
            return "数组为空！";
        }
        String submissionId = dataSubmissionYys.get(0).getSubmissionId();
        if(StringUtils.isEmpty(submissionId)){
            return "id 为空！";
        }
        DataSubmissionYyExample example = new DataSubmissionYyExample();
        example.createCriteria().andSubmissionIdEqualTo(submissionId);
        int count = dataSubmissionYyMapper.deleteByExample(example);
        if(count < 0){
            return "清理数据异常！";
        }
        count = dataSubmissionYyMapper.batchInsertDataSubmissionYy(dataSubmissionYys);
        if(count < 1){
            throw new Exception("插入数据异常！");
        }
        return "";
    }
}
